package com.inspire.common.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @author ：inspire
 * @date ：Created in 2022/8/12 14:13
 * @description：
 * @modified By：inspire
 * @version:
 */
public class MsgDecoder extends ByteToMessageDecoder{
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        //第一个int类型表示状态，第二个int类型表示长度，总共8个字节不能少
        if(in.readableBytes() < 8) return;

        //启用读取索引
        in.markReaderIndex();

        MsgType msgType = MsgType.values()[in.readInt()];
        int length = in.readInt();

        //如果可读的字节长度小于消息中标记的长度字段值，则reset索引并return,对此消息不做任何处理
        if(in.readableBytes()< length) {
            in.resetReaderIndex();
            return;
        }

        byte[] bytes = new byte[length];
        //将in中剩下的字节读进bytes对象中
        in.readBytes(bytes);

        Msg msg = null;

        //reflection
        msg = (Msg)Class.forName("com.inspire.client01.tank." + msgType.toString() + "Msg").getDeclaredConstructor().newInstance();
		/*switch(msgType) {
		case TankJoin:
			msg = new TankJoinMsg();
			break;
		case TankStartMoving:
			msg = new TankStartMovingMsg();
			break;
		case TankStop:
			msg = new TankStopMsg();
			break;
		case Tank
		default:
			break;
		}*/

        msg.parse(bytes);
        out.add(msg);//交给channelRead0处理
    }
}
